package com.hyjx.framework.component.index;

import com.hyjx.framework.common.util.SpringBeanUtil;
import com.hyjx.framework.login.LoginService;
import com.hyjx.framework.service.ConfigManager;
import com.hyjx.framework.service.RightManager;
import com.hyjx.framework.service.SessionManager;
import com.hyjx.framework.service.SystemService;
import com.hyjx.framework.service.UserCenterService;
import com.hyjx.framework.service.model.CacheUser;
import com.hyjx.framework.uc.menu.MenuModel;
import com.hyjx.framework.uc.menu.MenuService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 框架公共地址控制器
 */
@Controller
@RequestMapping("/index")
public class IndexController {

    @Resource
    MenuService menuService;

    /**
     * 到登录页
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/gotoLogin", method = RequestMethod.GET)
    public ModelAndView gotoLogin(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/index/login");
        return mav;
    }

    /**
     * 到左侧
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/left", method = RequestMethod.GET)
    public ModelAndView left(HttpServletRequest request) {
        MenuModel model = new MenuModel();
        model.setValidity("Y");
        List<MenuModel> list = null;
        try {
            list = menuService.queryMenuModelList(model);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        ModelAndView mav = new ModelAndView("/framework/index/left");
        mav.addObject("list", list);
        return mav;
    }

    /**
     * 到右侧
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/right", method = RequestMethod.GET)
    public ModelAndView right(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/framework/index/right");
        return mav;
    }

    /**
     * 到头文件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/top", method = RequestMethod.GET)
    public ModelAndView top(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/framework/index/top");
        return mav;
    }

    /**
     * 到控制页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/control", method = RequestMethod.GET)
    public ModelAndView control(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/framework/index/control");
        return mav;
    }

    /**
     * 到导航页
     *
     * @param request
     * @return
     *
     * @throws SQLException
     */
    @RequestMapping(value = "/nav", method = RequestMethod.GET)
    public ModelAndView nav(HttpServletRequest request) throws SQLException {
        List<MenuModel> list = menuService.queryMenuLevelOne();
        ModelAndView mav = new ModelAndView("/framework/index/nav");
        mav.addObject("list", list);
        return mav;
    }

    /**
     * 到控制台
     *
     * @param request
     * @return
     *
     * @throws SQLException
     */
    @RequestMapping(value = "/console", method = RequestMethod.GET)
    public ModelAndView console(HttpServletRequest request) throws SQLException {
        ModelAndView mav = new ModelAndView("/login");
        if (UserCenterService.getCurrentUserInfo() != null) {
            LoginService loginService = (LoginService) SpringBeanUtil.getBean("loginService");
            mav = loginService.getCurrentHome();
        }
        return mav;
    }

    /**
     * 到首页
     *
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public ModelAndView home(HttpServletRequest request) {
        SessionManager.set("activeMenuId", "home");
        String home = "/framework/index/home";
        if ("2".equals(ConfigManager.getUiLayout())) {
            home = "/index_layout";
        }
        ModelAndView mav = new ModelAndView(home);
        return mav;
    }

    /**
     * 到某个一级菜单页
     *
     * @param request
     * @param menuId
     * @return
     */
    @RequestMapping(value = "/index")
    public ModelAndView index(HttpServletRequest request, String menuId) {
        SessionManager.set("activeMenuId", menuId);
        String indexurl = "/framework/index/index";
        if ("2".equals(ConfigManager.getUiLayout())) {
            //只给layout布局用
            CacheUser cacheUser = RightManager.getSysUsers().get(UserCenterService.getCurrentUserId());
            List<MenuModel> menuModels = cacheUser.getRightMenuMap().get(UserCenterService.getCurrentSubsys_id());
            request.setAttribute("usermenus", menuModels);
            indexurl = "/index_layout";
        }

        ModelAndView mav = new ModelAndView(indexurl);

        MenuModel menuModel = RightManager.getAllMenus().get(menuId);
        if (menuModel != null) {
            String indexFuncEntra = menuModel.getFunc_entra();
            if (indexFuncEntra == null || "".equals(indexFuncEntra)) {
                if ("1".equals(ConfigManager.getConfig("sys.menu.selectfirst"))) {
                    CacheUser cacheUser = RightManager.getSysUsers().get(UserCenterService.getCurrentUserId());
                    List<MenuModel> menuModels = cacheUser.getRightMenuMap().get(UserCenterService.getCurrentSubsys_id());
                    if (menuModels != null && menuModels.size() > 0) {
                        MenuModel currentMenu = null;
                        for (MenuModel mm : menuModels) {
                            if (mm.getMenu_code().equals(menuId)) {
                                currentMenu = mm;
                                break;
                            }
                        }

                        if (currentMenu != null) {
                            List<MenuModel> children = currentMenu.getChildren();
                            for (MenuModel menu : children) {
                                if (menu.getFunc_entra() != null) {
                                    indexFuncEntra = menu.getFunc_entra();
                                    break;
                                }
                            }
                        } else {
                            indexFuncEntra = "";
                        }

                    } else {
                        indexFuncEntra = "";
                    }
                } else {
                    indexFuncEntra = "";
                }
            } else {
                indexFuncEntra = indexFuncEntra.startsWith("http://") ? indexFuncEntra : SystemService.getBasePath() + indexFuncEntra;
            }
            SessionManager.set("indexFuncEntra", indexFuncEntra);
        }
        return mav;
    }

    /**
     * 返回类似  [{code:'01',name:'系统管理'},{code:'98',name:'示例demo'}] 的字符串
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/menunav", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public String menunav(HttpServletRequest request) {

        String sysId = UserCenterService.getCurrentSubsys_id();
        List<MenuModel> list = UserCenterService.getCurrUserRelaInfo().getRightMenuMap().get(sysId);
        if (list != null) {
            StringBuffer sb = new StringBuffer();
            sb.append("[");
            for (int i = 0; i < list.size(); i++) {
                MenuModel menu = list.get(i);
                if (i != 0) {
                    sb.append(",");
                }
                sb.append("{");
                sb.append("code:'" + menu.getMenu_code() + "'");
                sb.append(",name:'" + menu.getMenu_name() + "'");
                sb.append("}");
            }
            sb.append("]");
            return sb.toString();
        } else {
            return "[]";
        }
    }

    /**
     * 后端生成页面内左侧菜单的html，输出到前端（上端有一级菜单模式，本次生成为某一级菜单下的菜单）
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pagemenu", produces = "application/json; charset=utf-8")
    public String pagemenu(HttpServletRequest request) {
        //String basePath=SystemService.getBasePath();
        String sysId = UserCenterService.getCurrentSubsys_id();
        List<MenuModel> list = UserCenterService.getCurrUserRelaInfo().getRightMenuMap().get(sysId);
        String activeMenuId = SessionManager.getString("activeMenuId");
        List<MenuModel> pageMenuList = null;
        String menuName = null;
        String menuCode = null;

        //取当前一级下的所有子菜单
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                MenuModel menu = list.get(i);
                if (menu.getMenu_code().equals(activeMenuId)) {
                    menuName = menu.getMenu_name();
                    menuCode = menu.getMenu_code();
                    pageMenuList = menu.getChildren();
                    break;
                }
            }
        }

        //构建前端输出
        StringBuffer sb = new StringBuffer();
        if (pageMenuList != null) {
            sb.append("<script type=\"text/javascript\">function onMenuClick(menuUrl){rightFrame.window.location.href=menuUrl+\"&random=\"+Math.random();}</script>");
            sb.append("<div class=\"title\">" + menuName + "</div>");
            for (MenuModel menu : pageMenuList) {
                //只循环儿子节点
                if (menuCode.equals(menu.getMenu_parent_code())) {
                    if ("Y".equals(menu.getIs_leaf_node())) {
                        sb.append("<h1 class=\"menu1\"><a href=\"javascript:void(0);\" onclick=\"onMenuClick('" + RightManager.getEntraWithRandom(menu.getFunc_entra()) + "')\" >" + menu.getMenu_name() + "</a></h1>");
                        sb.append("<ul class=\"left-ul\"></ul>");
                    } else {
                        sb.append("<h1 class=\"menu1\"><a href=\"javascript:void(0);\">" + menu.getMenu_name() + "</a></h1>");
                        sb.append("<ul class=\"left-ul\">");
                        //增加下级
                        for (MenuModel menu2 : pageMenuList) {
                            //只循环儿子节点
                            if (menu.getMenu_code().equals(menu2.getMenu_parent_code())) {
                                sb.append("<li>");
                                if ("Y".equals(menu2.getIs_leaf_node())) {
                                    sb.append("<h2 class=\"menu2\"><a href=\"javascript:void(0);\" onclick=\"onMenuClick('" + RightManager.getEntraWithRandom(menu2.getFunc_entra()) + "')\" >" + menu2.getMenu_name() + "</a></h2>");
                                } else {
                                    sb.append("<h2 class=\"menu2\"><a href=\"javascript:void(0);\">" + menu2.getMenu_name() + "</a></h2>");

                                    for (MenuModel menu3 : pageMenuList) {
                                        //只循环儿子节点
                                        if (menu2.getMenu_code().equals(menu3.getMenu_parent_code())) {
                                            sb.append("<h3 class=\"menu3\"><a href=\"javascript:void(0);\" onclick=\"onMenuClick('" + RightManager.getEntraWithRandom(menu2.getFunc_entra()) + "')\" >" + menu2.getMenu_name() + "</a></h3>");
                                        }
                                    }
                                }
                            }
                        }
                        sb.append("</ul>");
                    }
                }
            }
        }
        return sb.toString();
    }

    /**
     * 后端生成页面内左侧菜单的html，输出到前端（上端无一级菜单模式，本次生成为所有菜单）
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pagemenu2", produces = "application/json; charset=utf-8")
    public String pagemenu2(HttpServletRequest request) {
        String basePath = SystemService.getBasePath();
        String sysId = UserCenterService.getCurrentSubsys_id();
        List<MenuModel> list = UserCenterService.getCurrUserRelaInfo().getRightMenuMap().get(sysId);

        List<MenuModel> pageMenuList = new ArrayList<MenuModel>();
        String menuName = "";
        String rootCode = "#";

        //取当前一级下的所有子菜单
        for (int i = 0; i < list.size(); i++) {
            MenuModel menu = list.get(i);
            List<MenuModel> children = menu.getChildren();
            if (children != null) {
                pageMenuList.addAll(children);
            }
        }
        pageMenuList.addAll(list);
        Collections.sort(pageMenuList);

        //构建前端输出
        StringBuffer sb = new StringBuffer();
        sb.append("<div class=\"title\">" + "</div>");
        String funcEntra = null;
        for (MenuModel menu : pageMenuList) {
            //只循环儿子节点
            String pCode = menu.getMenu_parent_code() == null ? "#" : menu.getMenu_parent_code();
            if (rootCode.equals(pCode)) {
                String iconName = menu.getIconname() == null ? "menu1-2-icon1.png" : menu.getIconname();
                funcEntra = menu.getFunc_entra();
                String aTag = null;
                if (funcEntra == null || "".equals(funcEntra)) {
                    aTag = "<a href=\"javascript:void(0);\">" + "<img class=\"icon\" src=\"images/" + iconName + "\"/>" + menu.getMenu_name() + "</a>";
                } else {
                    aTag = "<a href=\"" + (funcEntra != null && funcEntra.startsWith("http://") ? funcEntra : basePath + funcEntra) + "\" target=\"rightFrame\">" + "<img class=\"icon\" src=\"images/" + iconName + "\" />" + menu.getMenu_name() + "</a>";
                }

                sb.append("<h1 class=\"menu1\" title=\"" + menu.getMenu_name() + "\">" + aTag + "</h1>");
                sb.append("<ul class=\"left-ul\">");
                //增加下级
                for (MenuModel menu2 : pageMenuList) {
                    //只循环儿子节点
                    if (menu.getMenu_code().equals(menu2.getMenu_parent_code())) {
                        funcEntra = menu2.getFunc_entra();
                        aTag = "<a href=\"" + (funcEntra != null && funcEntra.startsWith("http://") ? funcEntra : basePath + funcEntra) + "\" target=\"rightFrame\">" + menu2.getMenu_name() + "</a>";
                        sb.append("<li>");
                        sb.append("<h2 class=\"menu2\" title=\"" + menu2.getMenu_name() + "\">" + aTag + "</h2>");
                    }
                }
                sb.append("</ul>");
            }
        }
        return sb.toString();
    }
}